package net.sudot.chess.business.model;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.math.BigDecimal;
import java.time.Instant;

/**
 * 充值订单
 * <pre>
 *     充值订单充值的是金豆
 * </pre>
 *
 * @author tangjialin on 2018-03-21.
 */
@Getter
@Setter
@Accessors(chain = true)
@Entity
public class OrderRecharge extends BaseOrder<OrderRecharge> {

    /** 状态 */
    public enum Status {
        /** */ PENDING_PAYMENT("待支付"),
        /** */ PAID("已付款"),
        /** */ COMPLETED("已完成"),
        /** */ CANCELED("已取消");
        private String memo;

        Status(String memo) {
            this.memo = memo;
        }

        public String memo() {
            return memo;
        }
    }

    /** 状态 */
    @Enumerated(EnumType.STRING)
    private OrderRecharge.Status status;
    /** 得到的金豆 */
    private BigDecimal receiveAmount;
    /** 过期时间 */
    private Instant expire;

    /**
     * 获取应付金额
     *
     * @return 应付金额
     */
    @Override
    @Transient
    public BigDecimal getPayableAmount() {
        if (hasExpired() || getStatus().ordinal() >= OrderGame.Status.COMPLETED.ordinal()) {
            return BigDecimal.ZERO;
        }
        BigDecimal amountPayable = getPaymentAmount().subtract(getPaidAmount());
        return amountPayable.compareTo(BigDecimal.ZERO) > 0 ? amountPayable : BigDecimal.ZERO;
    }

    /**
     * 获取应退金额
     *
     * @return 应退金额
     */
    @Override
    @Transient
    public BigDecimal getRefundableAmount() {
        if (hasExpired() || getStatus().ordinal() > OrderGame.Status.COMPLETED.ordinal()) {
            BigDecimal refundableAmount = getPaidAmount();
            return refundableAmount.compareTo(BigDecimal.ZERO) >= 0 ? refundableAmount : BigDecimal.ZERO;
        }
        if (OrderGame.Status.COMPLETED.equals(getStatus())) {
            BigDecimal refundableAmount = getPaidAmount().subtract(getPaymentAmount());
            return refundableAmount.compareTo(BigDecimal.ZERO) >= 0 ? refundableAmount : BigDecimal.ZERO;
        }
        return BigDecimal.ZERO;
    }

    /**
     * 判断是否已过期
     *
     * @return 是否已过期
     */
    @Override
    @Transient
    public boolean hasExpired() {
        Instant expire = getExpire();
        return expire != null && expire.isBefore(Instant.now());
    }
}